﻿using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
using DBConnectionLib;
using System.Collections.Specialized;

namespace DBSourceToolsLib
{
    public class DatabaseDropScript : DatabaseScript
    {
        public DatabaseDropScript(DatabaseEx oParentDatabase, DatabaseEx oSourceDatabase)
            : base(oParentDatabase, oSourceDatabase)
        {
            this.ScriptFilePath = oParentDatabase.BaseDirectory + "\\" + oParentDatabase.DatabaseName + "_DropDB.sql";
            base.LoadScriptFromDisk();
        }
        public override void WriteDefaultScript()
        {
            if (this.m_SourceDatabase != null)
            {
                try
                {
                    ScriptDropFromDatabase();
                }
                catch (Exception ex)
                {
                    ScriptDropFromStandard();
                }
            }
            
        }

        private void ScriptDropFromStandard()
        {
                        base.ScriptText = String.Format(@"IF  EXISTS (SELECT name FROM sys.databases WHERE name = N'{0}')
DROP DATABASE [{0}]
GO
", this.m_SourceDatabase.DatabaseName);
            base.WriteScript();

        }

        private void ScriptDropFromDatabase()
        {
            Microsoft.SqlServer.Management.Smo.Server oServer = this.m_SourceDatabase.GetSmoServer();
            Microsoft.SqlServer.Management.Smo.Database oDatabase = this.m_SourceDatabase.GetSmoDatabase(oServer);
            Microsoft.SqlServer.Management.Smo.ScriptingOptions oScriptingOptions = new Microsoft.SqlServer.Management.Smo.ScriptingOptions();
            oScriptingOptions.ExtendedProperties = UserSettings.Instance().UseExtendedProperties;
            oScriptingOptions.AnsiFile = UserSettings.Instance().UseANSII;

            oScriptingOptions.ScriptDrops = true;
            oScriptingOptions.IncludeIfNotExists = true;
            oScriptingOptions.FileName = this.ScriptFilePath;
            StringCollection myStrColl = new StringCollection();
            oDatabase.Script(oScriptingOptions);
        }

        

    }
}
